package com.topscore.uke.ui.activities;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.flyco.tablayout.SegmentTabLayout;
import com.flyco.tablayout.listener.OnTabSelectListener;
import com.kingja.loadsir.callback.Callback;
import com.kingja.loadsir.core.LoadService;
import com.kingja.loadsir.core.LoadSir;
import com.timehop.stickyheadersrecyclerview.StickyRecyclerHeadersAdapter;
import com.timehop.stickyheadersrecyclerview.StickyRecyclerHeadersDecoration;
import com.topscore.uke.R;
import com.topscore.uke.entities.MemberTagEntity;
import com.topscore.uke.entities.MemberTagType;
import com.topscore.uke.entities.MemberTagValue;
import com.topscore.uke.mvp.contractors.GetMemberTagsContractor;
import com.topscore.uke.mvp.presenters.GetMemberTagsInfoPresenter;
import com.topscore.uke.ui.ToolBarCompatActivity;
import com.topscore.uke.ui.dialog.BottomListSelector;
import com.topscore.uke.utils.SnackBarUtil;
import com.topscore.uke.utils.StringUtil;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

public class MemberTagInfoActivity extends ToolBarCompatActivity implements GetMemberTagsContractor.View {

    @Bind(R.id.tab_layout)
    SegmentTabLayout tabLayout;
    @Bind(R.id.root_recycler)
    RecyclerView rootRecycler;
    @Bind(R.id.root_layout)
    LinearLayout rootLayout;


    private LinearLayoutManager mLayoutManager;

    private RootAdapter mRootAdapter;


    private GetMemberTagsInfoPresenter mTagsInfoPresenter;

    private BottomListSelector mConstellationSelector;

    private MenuItem mEditMenuItem;
    private boolean mIsEditing = false;

    private String mId;

    private LoadService mLoadService;

    private final int _SelectTag = 2001;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_member_tag_info);
        ButterKnife.bind(this);
        setCentralTitle("会员标签");
        mId = getIntent().getStringExtra("id");
        initViews();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_edit, menu);
        mEditMenuItem = menu.findItem(R.id.action_edit);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_edit:
                if (mIsEditing) {
                    mEditMenuItem.setTitle("编辑");
                    mIsEditing = false;
                } else {
                    mEditMenuItem.setTitle("完成");
                    mIsEditing = true;
                }
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    private void initViews() {
        mRootAdapter = new RootAdapter();
        mLayoutManager = new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false);
        StickyRecyclerHeadersDecoration stickyRecyclerHeadersDecoration = new StickyRecyclerHeadersDecoration(mRootAdapter);
        rootRecycler.setLayoutManager(mLayoutManager);
        rootRecycler.addItemDecoration(stickyRecyclerHeadersDecoration);
        rootRecycler.setAdapter(mRootAdapter);
        mLoadService = LoadSir.getDefault().register(rootRecycler, new Callback.OnReloadListener() {
            @Override
            public void onReload(View v) {
                mTagsInfoPresenter.getTags(mId);
            }
        });
        rootRecycler.addOnScrollListener(new RecyclerView.OnScrollListener() {
//            @Override
//            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
//
//                super.onScrollStateChanged(recyclerView, newState);
//            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                LinearLayoutManager layoutManager = (LinearLayoutManager) rootRecycler.getLayoutManager();
                super.onScrolled(recyclerView, dx, dy);
                int visiblePosition = layoutManager.findFirstVisibleItemPosition();
                tabLayout.setCurrentTab(visiblePosition);
            }
        });

        tabLayout.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelect(int position) {
                rootRecycler.scrollToPosition(position);
            }

            @Override
            public void onTabReselect(int position) {

            }
        });

        mTagsInfoPresenter = new GetMemberTagsInfoPresenter(this);
        mTagsInfoPresenter.getTags(mId);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == _SelectTag) {
            if (resultCode == RESULT_OK && data != null
                    && data.getParcelableExtra("tag_type") instanceof MemberTagType) {
                MemberTagType memberTagType = data.getParcelableExtra("tag_type");
                for (int i = 0; i < mRootAdapter.getData().size(); i++) {
                    MemberTagEntity entity = mRootAdapter.getData().get(i);
                    for (int j = 0; j < entity.getTagType().size(); j++) {
                        if (memberTagType.getTagCode().equals(entity.getTagType().get(j).getTagCode())){
                            mRootAdapter.getData().get(i).getTagType().get(j).setTagValues(memberTagType.getTagValues());
                            mRootAdapter.notifyItemChanged(i,"tag_values");
                        }
                    }
                }
            }
        }
    }

    //    private void smoothRecyclerToPosition(int position) {
//        int firstItem = mLayoutManager.findFirstVisibleItemPosition();
//        int lastItem = mLayoutManager.findLastVisibleItemPosition();
//        if (position <= firstItem) {
//            rootRecycler.scrollToPosition(position);
//        } else if (position <= lastItem) {
//            int top = rootRecycler.getChildAt(position - firstItem).getTop();
//            rootRecycler.scrollBy(0, top);
//        } else {
//            rootRecycler.scrollToPosition(position);
//            mIsMoving = true;
//        }
//    }

//    private void initMultiAdapter() {
//        int[] itemTypes = {_BasicInfo, _BodyInfo, _FootInfo, _LiveInfo};
//        mMultiItemList = new ArrayList<>();
//        for (int i = 0; i < itemTypes.length; i++) {
//            mMultiItemList.add(new MultiItem(itemTypes[i]));
//        }
//        mAdapter = new MultiAdapter(mMultiItemList);
//    }

    @Override
    public void onLoading(String loadingMessage) {
        showLoadingDialog(loadingMessage);
    }

    @Override
    public void onLoadFinished() {
        dismissLoadingDialog();
        mLoadService.showSuccess();
    }

    @Override
    public void onFail(int code, String errorMessage) {
        SnackBarUtil.getInstance(rootLayout)
                .showShort(errorMessage)
                .setAction("重试", view ->
                        mTagsInfoPresenter.getTags(mId)
                )
                .show();
    }

    @Override
    public void setTabs(String[] tabTitles) {
        tabLayout.setTabData(tabTitles);
    }

    @Override
    public LoadService getLoadService() {
        return mLoadService;
    }

    @Override
    public BaseQuickAdapter getRootRecycler() {
        return mRootAdapter;
    }

    private class RootAdapter extends BaseQuickAdapter<MemberTagEntity, BaseViewHolder>
            implements StickyRecyclerHeadersAdapter<RecyclerView.ViewHolder> {

        public RootAdapter() {
            super(R.layout.member_tags_item, new ArrayList<>());
        }

        @Override
        public void onBindViewHolder(BaseViewHolder holder, int position, List<Object> payloads) {
//            super.onBindViewHolder(holder, position, payloads);
            if (payloads.isEmpty()){
                super.onBindViewHolder(holder,position);
            }else {
                MemberTagEntity item = getData().get(position);
                RecyclerView recyclerView = holder.getView(R.id.tabs_recycler);
                recyclerView.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false));
                TagTypeAdapter adapter = new TagTypeAdapter(item.getTagType());
                View emptyView = getLayoutInflater().inflate(R.layout.member_tag_type_empty, (ViewGroup) recyclerView.getParent(), false);
                ((TextView) emptyView.findViewById(R.id.empty_message)).setText("暂无" + item.getBasisDictionaryVo().getValueName() + "标签");
                adapter.setEmptyView(emptyView);
                recyclerView.setAdapter(adapter);
            }
        }

        @Override
        protected void convert(BaseViewHolder holder, MemberTagEntity item) {
//            holder.setText(R.id.tag_value_name_tv, item.getBasisDictionaryVo().getValueName());
            RecyclerView recyclerView = holder.getView(R.id.tabs_recycler);
            recyclerView.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false));
            TagTypeAdapter adapter = new TagTypeAdapter(item.getTagType());
            View emptyView = getLayoutInflater().inflate(R.layout.member_tag_type_empty, (ViewGroup) recyclerView.getParent(), false);
            ((TextView) emptyView.findViewById(R.id.empty_message)).setText("暂无" + item.getBasisDictionaryVo().getValueName() + "标签");
            adapter.setEmptyView(emptyView);
            recyclerView.setAdapter(adapter);
        }

        @Override
        public long getHeaderId(int i) {
            return getData().get(i).getBasisDictionaryVo().getValueSort();
        }

        @Override
        public RecyclerView.ViewHolder onCreateHeaderViewHolder(ViewGroup viewGroup) {
            View view = getLayoutInflater().inflate(R.layout.member_tag_sticky_header, viewGroup, false);
            return new VH(view);
        }

        @Override
        public void onBindHeaderViewHolder(RecyclerView.ViewHolder viewHolder, int i) {
            String title = getData().get(i).getBasisDictionaryVo().getValueName();
            VH vh = (VH) viewHolder;
            vh.textView.setText(title);
        }

        private class VH extends RecyclerView.ViewHolder {
            private TextView textView;

            public VH(View itemView) {
                super(itemView);
                textView = (TextView) itemView.findViewById(R.id.tag_value_name_tv);
            }
        }
    }

//    private class MultiAdapter extends BaseMultiItemQuickAdapter<MultiItem, BaseViewHolder> {
//
//        /**
//         * Same as QuickAdapter#QuickAdapter(Context,int) but with
//         * some initialization data.
//         *
//         * @param data A new list is created out of this one to avoid mutable list
//         */
//        public MultiAdapter(List<MultiItem> data) {
//            super(data);
//            addItemType(_BasicInfo, R.layout.member_tag_basic_layout);
//            addItemType(_BodyInfo, R.layout.member_tag_body_layout);
//            addItemType(_FootInfo, R.layout.member_tag_foot_layout);
//            addItemType(_LiveInfo, R.layout.member_tag_live_layout);
//        }
//
//        @Override
//        protected void convert(BaseViewHolder baseViewHolder, MultiItem multiItem) {
//            switch (multiItem.getItemType()) {
//                case _BasicInfo:
//                    mBasicLayout = baseViewHolder.getConvertView();
//                    baseViewHolder.getView(R.id.constellation_layout).setOnClickListener(v -> {
//                        if (mConstellationSelector == null) {
//                            String[] constellationTitles = new String[]{"白羊座",
//                                    "金牛座", "双子座", "巨蟹座", "狮子座", "处女座",
//                                    "天秤座", "天蝎座", "射手座", "摩羯座", "水瓶座", "双鱼座"};
//                            List<ConstellationEntity> constellationList = new ArrayList<>();
//                            for (int i = 0; i < constellationTitles.length; i++) {
//                                ConstellationEntity entity = new ConstellationEntity();
//                                entity.setTitle(constellationTitles[i]);
//                                constellationList.add(entity);
//                            }
//                            mConstellationSelector = new BottomListSelector(mContext,
//                                    "星座", constellationList)
//                                    .setCallBack((BottomListSelector.SelectorSingleCallBack<ConstellationEntity>) item ->
//                                            baseViewHolder.setText(R.id.constellation_tv, item.getTitle())
//                                    );
//                        }
//                        mConstellationSelector.show();
//
//                    });
//                    break;
//                case _BodyInfo:
//                    mBodyLayout = baseViewHolder.getConvertView();
//                    break;
//                case _FootInfo:
//                    mFootLayout = baseViewHolder.getConvertView();
//                    break;
//                case _LiveInfo:
//                    mLiveLayout = baseViewHolder.getConvertView();
//                    baseViewHolder.getView(R.id.focus_point).setOnClickListener(v -> {
//                        Intent intent = new Intent(mContext, MultiSelectTagActivity.class);
//                        startActivityForResult(intent, _MultiSelect_Focus);
//                    });
//                    break;
//            }
//        }
//    }

    private class TagTypeAdapter extends BaseQuickAdapter<MemberTagType, BaseViewHolder> {


        public TagTypeAdapter(List<MemberTagType> data) {
            super(R.layout.member_tag_subitem, data);
        }

        @Override
        protected void convert(BaseViewHolder holder, MemberTagType item) {
            if (holder.getLayoutPosition() == 0) {
                holder.getView(R.id.divider_view).setVisibility(View.GONE);
            } else {
                holder.getView(R.id.divider_view).setVisibility(View.VISIBLE);
            }
            holder.setText(R.id.tag_key_tv, item.getTagName());
            RecyclerView recyclerView = holder.getView(R.id.tag_value_recycler);
            recyclerView.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false));
            List<MemberTagValue> tagValues = new ArrayList<>();
            if (!StringUtil.isEmpty(item.getValue())) {
                String[] values = item.getValue().split(",");
                for (int i = 0; i < values.length; i++) {
                    for (int j = 0; j < item.getTagValues().size(); j++) {
                        if (values[i].equals(item.getTagValues().get(j).getValue()) || item.getTagValues().get(j).isSelected()) {
                            item.getTagValues().get(j).setSelected(true);
                            tagValues.add(item.getTagValues().get(j));
                        } else {
                            item.getTagValues().get(j).setSelected(false);
                            tagValues.remove(item.getTagValues().get(j));
                        }
                    }
                }
            }else {
                for (int i = 0; i < item.getTagValues().size(); i++) {
                    if (item.getTagValues().get(i).isSelected()){
                        tagValues.add(item.getTagValues().get(i));
                    }
                }
            }
            recyclerView.setAdapter(new BaseQuickAdapter<MemberTagValue, BaseViewHolder>(R.layout.member_tag_value_item, tagValues) {
                @Override
                protected void convert(BaseViewHolder helper, MemberTagValue item) {
                    helper.setText(R.id.tag_value_tv, item.getLabel());
                }
            });


            holder.itemView.setOnClickListener(view -> {
                if (mIsEditing) {
                    switch (item.getInputType()) {
                        case "checkbox":
                            Intent intent = new Intent(MemberTagInfoActivity.this, MultiSelectTagActivity.class);
                            intent.putExtra("tag_type", item);
                            startActivityForResult(intent, _SelectTag);
                            break;
                    }
                } else {
                    return;
                }
            });
        }
    }
}
